//
//  GlanceController.m
//  chanlin WatchKit Extension
//
//  Created by Ryan on 15-5-9.
//  Copyright (c) 2015年 chanlin. All rights reserved.
//

#import "GlanceController.h"
#import "NSObject+sgr.h"


@interface GlanceController()

@property (nonatomic,unsafe_unretained)BOOL isinit;

@end


@implementation GlanceController

- (void)awakeWithContext:(id)context {
    [super awakeWithContext:context];
    
    [NSTimer scheduledTimerWithTimeInterval:3600 target:self selector:@selector(loadNewElement) userInfo:nil repeats:YES];
    
   
    
}

- (void)willActivate {
    
    
  NSTimeInterval current=[[NSDate date] timeIntervalSince1970];
  double d=[[NSUserDefaults standardUserDefaults] doubleForKey:@"clwatchGlanceDate"];
 // NSInteger b=[[NSUserDefaults standardUserDefaults] integerForKey:@"clwatchDefaltTime"];
   
    if(fabs(current-d)>3600){
        [self performSelectorInBackground:@selector(loadNewElement) withObject:nil];
    }else{
        UIImage *img=[self getBGImgae];
        [self.imageGroup setBackgroundImage:img];
        [self.titleLabel setText:[self getDefaultTitle]];
        NSString *url=[[NSUserDefaults standardUserDefaults] stringForKey:@"clwatchDefaltUrl"];
        if(url){
            NSString *type=[[NSUserDefaults standardUserDefaults] stringForKey:@"clwatchDefalttype"];
            
            [self updateUserActivity:@"glance" userInfo:@{@"url":url,@"type":(type?type:@"0")} webpageURL:nil];
        }
    }
    
   // [self loadNewElement];

//    UIImage *img=[self getBGImgae];
//    [self.imageGroup setBackgroundImage:img];
//    [self.titleLabel setText:[self getDefaultTitle]];
    
  }

- (void)didDeactivate {
    // This method is called when watch view controller is no longer visible
    [super didDeactivate];
}

- (NSString *)getDefaultTitle{
    NSString *title=[[NSUserDefaults standardUserDefaults] stringForKey:@"clwatchDefaltTitle"];
    if(!title){
        return @"";
    }else{
        return title;
    }
}

- (UIImage *)getBGImgae{
    
     NSArray * paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *path=[[paths sgrGetStringForIndex:0] stringByAppendingPathComponent:@"imageData"];
    if([[NSFileManager defaultManager] fileExistsAtPath:path]){
       return  [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL fileURLWithPath:path]]];
    }else{
        return  nil;
    }
    
    
}

- (void)loadNewElement{
    NSString *str=@"http://appv2.chanlin.org/e/app/view_watch.php";
    NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:str]];
    NSData *data= [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    if(data){
        NSObject *obj=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        NSDictionary *data2=[obj sgrGetDictionaryForKey:@"data"];
        NSString *imageStr=[data2 sgrGetStringForKey:@"titlepic"];
        if(!imageStr) return;
        NSData *imageData=[NSData dataWithContentsOfURL:[NSURL URLWithString:imageStr]];
        if(!imageData) return;
        UIImage *image=[UIImage imageWithData:imageData];
        if(!image) return;
        [self.imageGroup setBackgroundImage:image];
        [self.titleLabel setText:[data2 sgrGetStringForKey:@"smalltext"]];
        NSString *url=[data2 sgrGetStringForKey:@"url"];
        
        NSString *type=[data2 sgrFGetStringForKey:@"type"];
        if(url)
            [self updateUserActivity:@"glance" userInfo:@{@"url":url,@"type":(type?type:@"0")} webpageURL:nil];
        
        NSArray * paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
        NSString *path=[[paths sgrGetStringForIndex:0] stringByAppendingPathComponent:@"imageData"];
        
        if([[NSFileManager defaultManager] fileExistsAtPath:path]){
            [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
        }
        [imageData writeToFile:path atomically:YES];
        
        if(url)
        [[NSUserDefaults standardUserDefaults] setObject:url forKey:@"clwatchDefaltUrl"];
        if(type)
            [[NSUserDefaults standardUserDefaults] setObject:type forKey:@"clwatchDefalttype"];
        [[NSUserDefaults standardUserDefaults] setInteger:[[obj sgrGetStringForKey:@"frequency"] integerValue]
                                                   forKey:@"clwatchDefaltTime"];
        [[NSUserDefaults standardUserDefaults] setObject:[data2 sgrGetStringForKey:@"smalltext"] forKey:@"clwatchDefaltTitle"];
        [[NSUserDefaults standardUserDefaults] setDouble:[[NSDate date] timeIntervalSince1970] forKey:@"clwatchGlanceDate"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }else{
        UIImage *img=[self getBGImgae];
        [self.imageGroup setBackgroundImage:img];
        [self.titleLabel setText:[self getDefaultTitle]];
        NSString *url=[[NSUserDefaults standardUserDefaults] stringForKey:@"clwatchDefaltUrl"];
        if(url){
            NSString *type=[[NSUserDefaults standardUserDefaults] stringForKey:@"clwatchDefalttype"];
            
            [self updateUserActivity:@"glance" userInfo:@{@"url":url,@"type":(type?type:@"0")} webpageURL:nil];
        }
    }
    
    
}



@end



